import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Form, Table, Modal, Spin, Button, message, Tooltip } from 'antd';
import { routerRedux } from 'dva/router';
import styles from './index.less';

const FormItem = Form.Item;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js',
});
@connect(({ process, loading }) => ({
  process,
  loading: loading.effects['knowledgeBaseSharing/fetch'],
}))
class KnowledgeBaseSharing extends Component {
  constructor(props) {
    super(props);
    this.state = {
      knowledgeList: [],
      total: 0,
      page: 1,
      pageSize: 10,
    };
  }

  // eslint-disable-next-line react/sort-comp
  fetche = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'knowledgeBaseSharing/fetch',
        payload: { robotId: currentUser.robotId,page:this.state.page,limit:this.state.pageSize },
        callback: res => {

          let val = res.items;
          val.map((item, index) => (item['key'] = index));
          this.setState({
            knowledgeList: val,
            login: false,
            total: res.total,
            page: 1,
          });
        },
      });
    });
  };

  componentDidMount() {
    this.fetche();
  }

  handleDelete = item => {

    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/knowledge/knowledgeBaseSharing/Edit',
        params: { id: item },
      })
    );
  };

  handleDeletes = item => {

    Modal['confirm']({
      title: '删除任务',
      content: '确定删除吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'knowledgeBaseSharing/fetchd',
            payload: { sharedCategoryId: item._id },
            callback: res => {

              if (res.status === true) {
                message['success']('执行成功！');
                this.fetche();
              }
              if (res.status === false) {
                message['error']('执行失败！');
              }
              this.fetche();
            },
          });
        });
      },
      onCancel() {

      },
    });
  };

  onChangeA = val => {
    // 页数选择

    this.setState({
      page: val,
    },()=>{
      this.fetche()
    });
  };

  onShowSizeChangeA = (current, pageSize) => {

    this.setState({
      pageSize,
    },()=>{
      this.fetche()
    });
  };

  enumeration = () => {
    // '/knowledge/antistopReply/edit'
    const { dispatch } = this.props;
    dispatch(
      routerRedux.push({
        pathname: '/knowledge/knowledgeBaseSharing/add',
        params: { id: 'tcx' },
      })
    );
  };

  lessdata = () => {
    const columns = [
      {
        title: '用户名',
        width: 'calc(30vw)',
        dataIndex: 'nickName',
      },
      {
        title: '用户账号',
        width: 'calc(40vw)',
        dataIndex: 'name',
      },
      {
        title: '操作',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <div
                className={styles.buttongl}
                onClick={text => {
                  this.handleDelete(item);
                }}
              >
                <MyIcon style={{ marginRight: 5 }} type="icon-bi" />
                <FormattedMessage id="app.customDictionary.edit" defaultMessage="Edit" />
              </div>
              <div
                style={{ marginLeft: 10, background: '#e8313b' }}
                className={styles.buttongl}
                onClick={text => {
                  this.handleDeletes(item);
                }}
              >
                <span>
                  <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span>
                <span>
                  {' '}
                  <FormattedMessage id="app.customDictionary.out" defaultMessage="out" />
                </span>
              </div>
            </div>
          );
        },
      },
    ];
    return (
      <div className="tableyc">
        <Spin spinning={this.state.login}>
          <Table
            className="zdyTable"
            columns={columns}
            dataSource={this.state.knowledgeList} //数据
            onChange={this.handleChange}
            pagination={{
              // 分页
              total: this.state.total,
              pageSize: this.state.pageSize, // 显示几条一页
              defaultPageSize: this.state.page, // 当前页
              showSizeChanger: true, // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.onChangeA,
              onShowSizeChange: this.onShowSizeChangeA,
            }}
          />
        </Spin>
      </div>
    );
  };

  render() {
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div className={styles.backgroundp}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, color: '#4B5475', fontWeight: 600 }} xs={24}>
                <div className={styles.title}>
                  <span>知识库共享{`(${this.state.total})`}</span>
                  <span style={{ marginLeft: 2, paddingTop: 2 }}>
                    <Tooltip
                      placement="top"
                      title="即把本账号机器人的部分或全部知识点分享给其他账号机器人使用。被共享账号机器人可以使用并修改共享知识点的答案。"
                      arrowPointAtCenter
                    >
                      <Icon type="info-circle" />
                    </Tooltip>
                  </span>
                </div>
              </Col>
            </Row>
            <Card bordered={false}>
              <div className={styles.fromColumn}>
                <div className="zdyButtonA">
                  <Button onClick={this.enumeration} type="primary" icon="plus">
                    <FormattedMessage
                      id="app.knowledgeBaseSharing.addKnowledge"
                      defaultMessage="add"
                    />
                  </Button>
                </div>
              </div>
              {this.lessdata()}
            </Card>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(KnowledgeBaseSharing));
